package com.tanhua.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.manager.domain.Admin;
import com.tanhua.manager.utils.AdminHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String TOKEN_PREFIX = "MANAGE_TOKEN_";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (authorization==null){
            response.setStatus(401);
            return false;
        }
        String token = authorization.replace("Bearer ", "");
        Admin admin = findAdminByToken(token);
        if (admin==null){
            response.setStatus(401);
            return false;
        }
        AdminHolder.setAdmin(admin);
        AdminHolder.setToken(token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.removeAdmin();
    }

    public Admin findAdminByToken(String token) {
        String adminJson = redisTemplate.opsForValue().get(TOKEN_PREFIX + token);
        if (adminJson==null){
            return null;
        }
        Admin admin = JSON.parseObject(adminJson, Admin.class);
        return admin;
    }
}
